package pro.ticktock.tools.mbconv;

import pro.ticktock.tools.mbconv.AbstractPass;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lambert on 2017/5/29.
 */
public class Pass7 extends AbstractPass {
  BufferedWriter bulkWriter;
  protected Pass7(String origSrcFileName, String srcFileName) throws IOException {
    super(origSrcFileName, srcFileName);
  }

  protected void preProcess() {

    File f = new File(MusciBibleConverter.getRootDir() + "\\pages\\");
    if (!f.exists() || !f.isDirectory()) {
      f.mkdir();
    }

    try {
      bulkWriter = new BufferedWriter(new FileWriter(new File(getFullName("bulk.data"))));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private final String PAGE_PREFIX = "href";

  @Override
  protected void doProcess() throws IOException {

    List<String> adjustedOL = new ArrayList<>();
    List<String> failedAdjustedOL = new ArrayList<>();


    resultWriter.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" +
            "<title>Music Bible</title></head>\n" +
            "\n" +
            "<frameset cols=\"25%,75%\">\n" +
            "\n" +
            "  <frame name=\"title\" src=\"title.html\">\n" +
            "  <frame name=\"content\" src=\"content.html\">\n" +
            "\n" +
            "</frameset>\n" +
            "\n" +
            "</html>");

    String line;
    int id = 0;
    BufferedWriter titleWriter =
            new BufferedWriter(new FileWriter(new File(getFullName("title.html"))));
    BufferedWriter contentWriter =
            new BufferedWriter(new FileWriter(new File(getFullName("content.html"))));
    try {
      String hrefId = null;
      StringBuffer pageContent = createPageHead();
      while ((line = srcReader.readLine()) != null) {
        if (line.startsWith(Pass2.CH_TITLE_MARK)) {
          if (hrefId != null) {
            addPageEndAndSave(hrefId, pageContent, false);
          }

          String enLine = srcReader.readLine();
          pageContent = createPageHead();
          pageContent.append("<div align='center'><font size='5'>" + line.substring(Pass2.CH_TITLE_MARK.length()) + "<br/>\n");

          hrefId = PAGE_PREFIX + ++id;
          titleWriter.append("<a href=\"pages/" + hrefId + ".html\" target=\"content\">").append(line.substring(Pass2.CH_TITLE_MARK.length())).append("</a><br/>\n");
          pageContent.append(enLine.substring(Pass2.EN_TITLE_MARK.length()) + "</font></div>\n");
        } else if (line.startsWith(Pass2.CH_ARTIST_MARK)) {
          if (hrefId != null) {
            addPageEndAndSave(hrefId, pageContent, false);
          }

          String enLine = srcReader.readLine();
          pageContent = createPageHead();
          pageContent.append("<div align='center'><font size='5'>" + line.substring(Pass2.CH_ARTIST_MARK.length()) + "<br/>\n");

          hrefId = PAGE_PREFIX + ++id;
          titleWriter.append("<a href=\"pages/" + hrefId + ".html\" target=\"content\">").append(line.substring(Pass2.CH_ARTIST_MARK.length())).append("</a><br/>\n");
          pageContent.append(enLine.substring(Pass2.EN_ARTIST_MARK.length()) + "</font></div>\n");
        } else {
          if (hrefId != null) {
            //line = line.replaceAll(" ", "&nbsp;");
            pageContent.append("<p>");
            int lastEnd = 0;
            int idx = line.indexOf(Pass6.LIST_MARK, 0);
            boolean listStarted = false;
            while (idx >= 0) {
              pageContent.append(line.substring(lastEnd, idx));
              pageContent.append("\n<br/>");
              if (!listStarted) {
                pageContent.append("<ol>");
                listStarted = true;
              } else {
                pageContent.append("</li>");
              }

              int listStartIdx = idx + Pass6.LIST_MARK.length();
              boolean hasListNumber = true;
              int listNo = 0;
              boolean isLeadingList = false;
              int len = 0;
              if (line.substring(listStartIdx).startsWith(Pass6.NUMBER_NA_MARK)) {
                hasListNumber = false;
                if (line.substring(listStartIdx + Pass6.NUMBER_NA_MARK.length()).startsWith(Pass6.LEADING_LIST_MARK)) {
                  isLeadingList = true;
                }
              }
              if (hasListNumber) {
                len = Pass6.getListNumberLen(line, listStartIdx);
                listNo = Integer.parseInt(line.substring(listStartIdx, listStartIdx + len));
                isLeadingList = listNo == 1;
              }

              if (isLeadingList) {
                int paraIdx = pageContent.lastIndexOf("<p>");
                String currPara;
                if (paraIdx >= 0) {
                  currPara = pageContent.substring(paraIdx);
                } else {
                  paraIdx = 0;
                  currPara = pageContent.toString();
                }
                if (currPara.contains("<li>")) {
                  int lastDotIdx = Math.max(currPara.lastIndexOf('。'), currPara.lastIndexOf('；'));
                  int lastLiIdx = currPara.lastIndexOf("<li>");
                  if (lastDotIdx > 0 && lastDotIdx > lastLiIdx) {
                    pageContent.insert(paraIdx + lastDotIdx + 1, "</li></ol>\n<p>　");
                    int lastCloseLiIdx = pageContent.lastIndexOf("</li>");
                    pageContent.delete(lastCloseLiIdx, lastCloseLiIdx + "</li>".length());
                    pageContent.append("<ol>");

                    if (!adjustedOL.contains(hrefId))
                      adjustedOL.add(hrefId);
                  } else {
                    failedAdjustedOL.add(hrefId);
                  }
                }
              }

              pageContent.append("<li>");
              if (hasListNumber) {
                pageContent.append("<b>" + listNo + "．</b>");
                lastEnd = listStartIdx + len + 1;
              } else {
                lastEnd = listStartIdx + Pass6.NUMBER_NA_MARK.length() + (isLeadingList ? Pass6.LEADING_LIST_MARK.length() : 0);
              }

              idx = line.indexOf(Pass6.LIST_MARK, lastEnd);
            }
            pageContent.append(line.substring(lastEnd));
            if (listStarted) {
              pageContent.append("</li></ol>");
            }
            pageContent.append("\n");
          }
        }
      }

      if (hrefId != null) {
        addPageEndAndSave(hrefId, pageContent, true);
      }

    } finally {
      titleWriter.close();
      contentWriter.close();

      File f = new File(MusciBibleConverter.getRootDir() + "\\" + "adjustedOL.html");
      try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {
        bw.write("<html><body>");
        bw.write("<h3>Adjusted Ordered List:</h3>");
        for (String href : adjustedOL) {
          bw.write("<a href=\"pages/" + href + ".html\">" + href + "</a><br/>\n");
        }

        bw.write("<h3>Adjust Failed Ordered List:</h3>");
        for (String href : failedAdjustedOL) {
          bw.write("<a href=\"pages/" + href + ".html\">" + href + "</a><br/>\n");

        }
        bw.write("<body></html>");
      }


      if (bulkWriter != null) {
        bulkWriter.close();
      }
    }
  }

  private StringBuffer createPageHead() {
    return new StringBuffer("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>")
            .append("<link href=\"common/list.css\" rel=\"stylesheet\" type=\"text/css\" />")
            .append("<style type=\"text/css\">\n" +
                    "body{font:15px/1.5 tahoma,arial,sans-serif;}\n" +
                    "</style>")
            .append("</head><body>");
  }

  private void addPageEndAndSave(String hrefId, StringBuffer content, boolean lastPage) throws IOException {

    int currLinkId = Integer.parseInt(hrefId.substring(PAGE_PREFIX.length()));
    String prev = currLinkId > 1 ? ("href" + (currLinkId - 1)) : null;
    String next = "href" + (currLinkId + 1);
    content.append("<br/><br/>\n")
            .append("<div align='center'>")
            .append(prev != null ? ("<a href='" + prev + ".html' id='prev'>前一页</a>") : "")
            .append((prev != null && !lastPage) ? "　　　　　　　　" : "")
            .append(lastPage ? "" : "<a href='" + next + ".html' id='next'>后一页</a>")
            .append("</div>\n")
            .append("<script type=\"text/javascript\" src=\"../nav.js\"></script>\n")
            .append("</body></html>");;

    try (BufferedWriter pageWriter =
                 new BufferedWriter(new FileWriter(new File(MusciBibleConverter.getRootDir() + "\\pages\\" + hrefId + ".html")))) {
      pageWriter.append(content);
    }

    if (bulkWriter != null) {
      bulkWriter.append(content + "\n\n");
    }
  }

  public String getResultFileName() {
    return srcFileNameNoExt + ".html";
  }
}
